import utils from '@/utils'
import api from '@/api'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: utils.cookie.getToken(),
    id: 0,
    name: '',
    roles: [],
    permissions: []
  }
}
const state = getDefaultState()

const mutations = {
  RESET_STATE(state) {
    state.token = ''
    state.roles = []
  },
  SET_TOKEN(state, v) { state.token = v },
  SET_ID(state, v) { state.id = v },
  SET_NAME(state, v) { state.name = v },
  SET_ROLES(state, v) { state.roles = v },
  SET_PERMISSIONS(state, v) { state.permissions = v }
}

const actions = {
  loginByUserName({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      api.user.loginByUserName({
        username: userInfo.username.trim(),
        password: userInfo.password
      }).then(resp => {
        const token = resp.data.token
        commit('SET_TOKEN', token)
        utils.cookie.setToken(token)
        resolve()
      }).catch(err => {
        reject(err)
      })
    })
  },
  getUserInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      api.user.getUserInfo(
      ).then(resp => {
        const { data } = resp
        if (!data) {
          return reject('Verification failed, please login again.')
        }
        commit('SET_ID', data.id)
        commit('SET_NAME', data.name)
        commit('SET_ROLES', data.roles)
        resolve(data)
      }).then(() => {
        return new Promise((resolve, reject) => {
          api.user.getPermission()
        })
      }).then(resp => {
        const { data } = resp
        commit('SET_PERMISSIONS', data)
        resolve(data)
      }).catch(err => {
        reject(err)
      })
    })
  },
  getUserRouters({ commit, state }) {
    return new Promise((resolve, reject) => {
      api.user.getUserRouters().then(resp => {
        // TODO@huanglf: 权限获取
        resolve()
      }).catch(err => {
        reject(err)
      })
    })
  },
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      api.user.logout().then(() => {
        utils.cookie.setToken()
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(err => {
        reject(err)
      })
    })
  },
  resetToken({ commit }) {
    return new Promise(resolve => {
      utils.cookie.setToken()
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

